package com.tfswue.hql.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tfswue.hql.entity.Book;
import com.tfswue.hql.service.Bookservice;
import com.tfswue.hql.util.DatabaseTestUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/book")
public class BookController {
    
    @Autowired
    private Bookservice bookservice;
    
    @Autowired
    private DatabaseTestUtil databaseTestUtil;

    /**
     * 查询所有图书
     */
    @GetMapping("/list")
    public Map<String, Object> getAllBooks() {
        Map<String, Object> result = new HashMap<>();
        try {
            List<Book> books = bookservice.list();
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", books);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 根据ID查询图书
     */
    @GetMapping("/{id}")
    public Map<String, Object> getBookById(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        try {
            Book book = bookservice.getById(id);
            if (book != null) {
                result.put("code", 200);
                result.put("message", "查询成功");
                result.put("data", book);
            } else {
                result.put("code", 404);
                result.put("message", "图书不存在");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 分页查询图书
     */
    @GetMapping("/page")
    public Map<String, Object> getBooksByPage(
            @RequestParam(defaultValue = "1") Integer current,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String author) {
        
        Map<String, Object> result = new HashMap<>();
        try {
            Page<Book> page = new Page<>(current, size);
            QueryWrapper<Book> queryWrapper = new QueryWrapper<>();
            
            if (name != null && !name.trim().isEmpty()) {
                queryWrapper.like("name", name);
            }
            if (author != null && !author.trim().isEmpty()) {
                queryWrapper.like("author", author);
            }
            
            Page<Book> bookPage = bookservice.page(page, queryWrapper);
            result.put("code", 200);
            result.put("message", "查询成功");
            result.put("data", bookPage);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "查询失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 添加图书
     */
    @PostMapping("/add")
    public Map<String, Object> addBook(@RequestBody Book book) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = bookservice.save(book);
            if (success) {
                result.put("code", 200);
                result.put("message", "添加成功");
                result.put("data", book);
            } else {
                result.put("code", 500);
                result.put("message", "添加失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "添加失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 更新图书
     */
    @PutMapping("/update")
    public Map<String, Object> updateBook(@RequestBody Book book) {
        Map<String, Object> result = new HashMap<>();
        try {
            if (book.getId() == null) {
                result.put("code", 400);
                result.put("message", "图书ID不能为空");
                return result;
            }
            
            boolean success = bookservice.updateById(book);
            if (success) {
                result.put("code", 200);
                result.put("message", "更新成功");
                result.put("data", book);
            } else {
                result.put("code", 500);
                result.put("message", "更新失败，图书可能不存在");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "更新失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 删除图书
     */
    @DeleteMapping("/delete/{id}")
    public Map<String, Object> deleteBook(@PathVariable Integer id) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = bookservice.removeById(id);
            if (success) {
                result.put("code", 200);
                result.put("message", "删除成功");
            } else {
                result.put("code", 500);
                result.put("message", "删除失败，图书可能不存在");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "删除失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 批量删除图书
     */
    @DeleteMapping("/batch")
    public Map<String, Object> deleteBatchBooks(@RequestBody List<Integer> ids) {
        Map<String, Object> result = new HashMap<>();
        try {
            boolean success = bookservice.removeByIds(ids);
            if (success) {
                result.put("code", 200);
                result.put("message", "批量删除成功");
            } else {
                result.put("code", 500);
                result.put("message", "批量删除失败");
            }
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "批量删除失败: " + e.getMessage());
        }
        return result;
    }

    // ========================================
    // 数据库诊断接口
    // ========================================

    /**
     * 数据库连接测试
     */
    @GetMapping("/test/connection")
    public Map<String, Object> testDatabaseConnection() {
        Map<String, Object> result = new HashMap<>();
        try {
            Map<String, Object> connectionTest = databaseTestUtil.testConnection();
            result.put("code", 200);
            result.put("message", "数据库连接测试完成");
            result.put("data", connectionTest);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "数据库连接测试失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 检查表是否存在
     */
    @GetMapping("/test/table")
    public Map<String, Object> checkTable() {
        Map<String, Object> result = new HashMap<>();
        try {
            Map<String, Object> tableCheck = databaseTestUtil.checkTableExists("book_hql");
            result.put("code", 200);
            result.put("message", "表检查完成");
            result.put("data", tableCheck);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "表检查失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 获取表结构信息
     */
    @GetMapping("/test/structure")
    public Map<String, Object> getTableStructure() {
        Map<String, Object> result = new HashMap<>();
        try {
            Map<String, Object> structure = databaseTestUtil.getTableStructure("book_hql");
            result.put("code", 200);
            result.put("message", "表结构获取完成");
            result.put("data", structure);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "表结构获取失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 测试查询功能
     */
    @GetMapping("/test/query")
    public Map<String, Object> testQuery() {
        Map<String, Object> result = new HashMap<>();
        try {
            Map<String, Object> queryTest = databaseTestUtil.testQuery("book_hql");
            result.put("code", 200);
            result.put("message", "查询测试完成");
            result.put("data", queryTest);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "查询测试失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 综合诊断
     */
    @GetMapping("/test/diagnosis")
    public Map<String, Object> fullDiagnosis() {
        Map<String, Object> result = new HashMap<>();
        try {
            Map<String, Object> diagnosis = databaseTestUtil.fullDiagnosis();
            result.put("code", 200);
            result.put("message", "综合诊断完成");
            result.put("data", diagnosis);
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "综合诊断失败: " + e.getMessage());
        }
        return result;
    }

    /**
     * 简单的数据库状态检查
     */
    @GetMapping("/test/status")
    public Map<String, Object> getDatabaseStatus() {
        Map<String, Object> result = new HashMap<>();
        try {
            // 尝试执行简单查询
            long count = bookservice.count();
            result.put("code", 200);
            result.put("message", "数据库状态正常");
            result.put("data", Map.of(
                "status", "healthy",
                "total_books", count,
                "timestamp", System.currentTimeMillis()
            ));
        } catch (Exception e) {
            result.put("code", 500);
            result.put("message", "数据库状态异常");
            result.put("data", Map.of(
                "status", "error",
                "error_message", e.getMessage(),
                "error_type", e.getClass().getSimpleName(),
                "timestamp", System.currentTimeMillis()
            ));
        }
        return result;
    }
}
